import Cookie from "@itwmw/miniprogram-cookie"
import { getUrl } from "./util";

/**
 * @typedef {Record<String,any>} IAnyObject
 */
/**
 * @callback requestGlobalOptions~requestSuccessCallback
 * @param {string|ArrayBuffer|IAnyObject} data
 * @param {Promise~resolve} resolve
 * @param {Promise~reject} reject
 * @returns {*}
 */
/**
 * @callback requestGlobalOptions~requestFailCallback
 * @param {string} errMsg
 * @param {Promise~resolve} resolve
 * @param {Promise~reject} reject
 * @returns {*}
 */

/**
 * 请求全局配置
 */
export const requestGlobalOptions = new class{
  /**
   * 成功回调
   * @type requestSuccessCallback
   */
  success

  /**
   * 失败回调
   * @type requestFailCallback
   */
  fail
}

/**
 * 发起Http请求
 * 
 * @param {String} uri      请求地址
 * @param {String} method   请求协议
 * @param {Object} data     请求数据
 * @param {Object} headers  附加协议头
 * @param {boolean} system  是否为系统接口
 *
 * @return {Promise}
 */
export default function request(uri = '', method = 'GET', data = {}, headers= {},system = false) {
  const url = getUrl(uri,system)
  return new Promise((resolve, reject) => {
    wx.showNavigationBarLoading()
    wx.request({
      url,
      data,
      method,
      header: Object.assign(
          {'content-Type':'application/x-www-form-urlencoded'},
          headers,
          {'cookie':Cookie.instance().getCookieText()}
      ),
      success({ data = {}, cookies } = {}) {
        Cookie.instance().addCookie(cookies)
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh()
        if (system){
          data?.code === 0 ? resolve(data) : reject(data.message || "")
        }else{
          typeof requestGlobalOptions.success == "function" && resolve(requestGlobalOptions.success(data, resolve, reject))
        }
        resolve(data)
      },
      fail: err => {
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh()
        !system && typeof requestGlobalOptions.fail == "function" && resolve(requestGlobalOptions.fail(data, resolve, reject))
        reject(err)
      }
    })
  })
}
